package org.big.rocktproducer.hard;

import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;

import java.util.Random;

// 事务监听器
@RocketMQTransactionListener
public class OrderTransactionListener implements RocketMQLocalTransactionListener {

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        try {
            // 执行本地事务

            System.out.println(msg.getPayload());
            System.out.println(msg.getHeaders());
            System.out.println(arg);
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        // 检查本地事务状态
        System.out.println(msg.getPayload());
        System.out.println(msg.getHeaders());
        String orderId = msg.getHeaders().get("orderId").toString();
        return new Random().nextBoolean() ?
                RocketMQLocalTransactionState.COMMIT :
                RocketMQLocalTransactionState.ROLLBACK;
    }
}